package com.masonluo.mlonlinejudge.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.masonluo.mlonlinejudge.constant.SystemConstant;
import com.masonluo.mlonlinejudge.entity.Solution;
import com.masonluo.mlonlinejudge.mapper.SolutionMapper;
import com.masonluo.mlonlinejudge.model.bo.SolutionBo;
import com.masonluo.mlonlinejudge.model.dto.SolutionDto;
import com.masonluo.mlonlinejudge.model.param.SolutionParam;
import com.masonluo.mlonlinejudge.model.vo.JudgeResultVo;
import com.masonluo.mlonlinejudge.model.vo.SolutionVo;
import com.masonluo.mlonlinejudge.result.Result;
import com.masonluo.mlonlinejudge.result.ResultCode;
import com.masonluo.mlonlinejudge.service.SolutionService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Scanner;

/**
 * @author masonluo
 * @date 2021/2/7 3:37 下午
 */
@RestController
@RequestMapping("/solutions")
public class SolutionController {

    @Autowired
    private SolutionService solutionService;

    @Autowired
    private SolutionMapper solutionMapper;

    @ApiOperation(value = "解决方案查找", notes = "根据当前登录者的Id返回所有解决方案")
    @GetMapping
    public Result<List<Solution>> findSolutionByUserId(HttpServletRequest request) {
        String token = request.getHeader(SystemConstant.TOKEN_HEADER);
        return new Result<>(ResultCode.OK, solutionService.listByUserId(-1));
    }


    @ApiOperation(value = "查找结果", notes = "根据soultionId返回Result")
    @ApiImplicitParam(name = "solutionId", value = "解决方案查找")
    @GetMapping("/findsolution/{solutionId}")
    public Result<JudgeResultVo> findResult(@PathVariable("solutionId") Integer solutionId) {
        return new Result<>(ResultCode.OK, solutionService.findJudgeResult(solutionId));
    }

    @ApiOperation(value = "提交解决方案", notes = "将Solution提交并返回Result对象")
    @PostMapping
    public Result<SolutionVo> submit(@RequestBody SolutionParam solutionParam,
                                     HttpServletRequest request) throws JsonProcessingException {
        String token = request.getHeader(SystemConstant.TOKEN_HEADER);
        SolutionDto dto = solutionMapper.paramToDto(solutionParam);
        dto.setUserToken(token);
        if (solutionParam.getExamAndExperimentId() > 0) {
//        判断上一次提交是否超过一分钟，如果未超过，返回错误
            int submitNextTime = solutionService.judgeSubmitNextTime(solutionParam.getUserId());
            if (submitNextTime != 0) {
                return Result.error("请在" + submitNextTime + "秒后进行提交");
            }
        }
        SolutionBo bo = solutionService.submit(dto);
        SolutionVo vo = solutionMapper.boToVo(bo);
        vo.setLanguage(solutionParam.getLanguage());
        Result<SolutionVo> res = new Result<>();
        res.setData(vo);
        res.setCode(ResultCode.ACCEPTED);
        res.setMessage("The solution has been accepted, wait for judge...");
        return res;
    }

    @ApiOperation(value = "查找最近一次提交代码", notes = "根据实验id、题目id和用户id返回最近一次提交代码")
    @GetMapping("/findsolution/{experimentId}/{problemId}/{userId}")
    public Result<String> findRecentSoureceCode(@PathVariable("experimentId") Integer experimentId,
                                                @PathVariable("problemId") Integer problemId,
                                                @PathVariable("userId") Integer userId) {
        String recentSoueceCode = solutionService.findRecentSourceCode(experimentId, problemId, userId);
        return Result.ok(recentSoueceCode);
    }

    @ApiOperation(value = "查看某实验题目的状态", notes = "根据实验id、题目id和用户id判断该题目的状态")
    @GetMapping("/judgeProblemStatus/{experimentId}/{problemId}/{userId}")
    public Result<String> judgeStatusByProblemIDAndUserId(@PathVariable("experimentId") Integer experimentId,
                                                          @PathVariable("problemId") Integer problemId,
                                                          @PathVariable("userId") Integer userId) {
        boolean successStatus = solutionService.judgeSuccessByProblemIDAndUserId(experimentId, problemId, userId);
        boolean doneStatus = solutionService.judgeDoneByProblemIDAndUserId(experimentId, problemId, userId);
        String status;
        if (doneStatus) {
            status = "NeverDo";
        } else {
            if (successStatus) {
                status = "PASS";
            } else {
                status = "FAIL";
            }
        }
        return Result.ok(status);
    }

}
